package com.matrix.common.component;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author 有点甜
 * @since 2025/8/10
 */
@Component
@RequiredArgsConstructor
public class DistributedIdGenerator {

    private final StringRedisTemplate redisTemplate;
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");

    public String nextId(String businessPrefix) {
        String date = LocalDateTime.now().format(DATE_FORMATTER);
        String key = "id_generator:" + businessPrefix + ":" + date;

        Long increment = redisTemplate.opsForValue().increment(key);

        if (increment != null && increment == 1) {
            redisTemplate.expire(key, 2, java.util.concurrent.TimeUnit.DAYS);
        }

        return String.format("%s_%s_%06d", businessPrefix.toUpperCase(), date, increment);
    }
}
